package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"pay_srv/models/mysql"
	"pay_srv/models/redis"
	"pay_srv/pkg"

	"pay_srv/internal/svc"
	"pay_srv/pay"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *pay.OrderAddRequest) (*pay.OrderAddResponse, error) {
	// todo: add your logic here and delete this line

	//订单创建查询商品是否存在
	var g mysql.Goods
	err := g.GetGoodsId(int(in.GoodsId))
	if err != nil {
		return nil, errors.New("商品不存在")
	}
	//获取虚拟库存
	stock := redis.GetGoodsStock(int(in.GoodsId))
	if stock < int64(in.Num) {
		return nil, errors.New("库存不足")
	}
	orderSn := uuid.NewString()
	price := g.Price * float64(in.Num)
	o := mysql.Order{
		UserId:  int(in.UserId),
		GoodsId: int(in.GoodsId),
		Num:     int(in.Num),
		OrderSn: orderSn,
		Amount:  price,
	}
	err = o.Add()
	if err != nil {
		return nil, errors.New("订单创建失败")
	}
	p := fmt.Sprintf("%.2f", price)
	url := pkg.AliPay(orderSn, p)
	return &pay.OrderAddResponse{OrderId: int32(o.ID), PayUrl: url}, nil
}
